<?php

/**
 * 登陆控制器
 *
 * @author mengyu.wang
 */

require 'CommonController.php';

class Admin_DayDataExcelHtmlController extends Admin_CommonController
{
    /**
     * 
     * 路径密码
     */
    private $_passid = 'yekbi123';
    private $_currAction = '';
    private $_productcode = '';
    private $_reportFile = '';

    /**
     * 初始化
     * 
     * @return void
     */
    public function init()
    {
        $this->_loginIsCheck = 0;
        parent::init();
        $this->view->title = $this->_configs['project']['systemName'] . " - 管理中心";
        $this->_model = new Application_Model_DayData();
        $this->_productModel = new Application_Model_PartnerProduct();
        $this->_ddhModel = new Application_Model_DayDataHtml();
    }
    /**
     * 获取月报表标题（默认为今天算起）
     */
    public function getMonthReportTitle()
    {
        return date('Y年m月',strtotime("now"));
    }
    /**
     * 获取报表TITLE(默认为昨天)
     */
    public function getFileDay()
    {
        return date('Y-m-d',strtotime("-1 day"));
    }
    
    /**
     * 获取日报发送时间(默认为昨天)
     */
    public function getPositionDay()
    {
        return date('Y-m-d',strtotime("-1 day"));
    }
    /**
     * 获取指定日期的时间戳(默认为昨天)
     */
    public function getPositionStamp()
    {
        return strtotime("-1 day");
    }
    /**
     * 获取月运营视图的开始结束时间(默认为-31，-1 )
     */
    public function getStartEndStamp()
    {
        $arr = array();
        $arr['startTime'] = strtotime("-31 days");
        $arr['endTime'] = strtotime("-1 day");
        return $arr;
    }

    /**
     * 报表导出，
     * 发送下载地址 $downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/yek_mob/data/dayData/';
     * 生成表格
     * 发送信息到邮箱
     * 
     * @return void
     */
    public function reportAction()
    {
         if($this->_request->get('id')!=$this->_passid){
            exit('非法访问');
        } else {
            $startTime = $this->getPositionDay();
            $year = date('Y');
            $month = date('m');
            $day = date('d');

            //获取搜有需要发送的报表产品编号
            $productCodes = $this->_productModel->reportProduct();
            
            foreach ($productCodes as $productCode) {
                $product = $this->_productModel->fetchRow("code = '{$productCode}'");
                $productName = $product['name'];
                //日运营表
                $opRow = $this->dayMemberType($startTime,$productCode);
                $keyOpArr = array('渠道类型', '订单金额', '订单量', 
                                  '客单价', '激活量', '激活用户提交订单量', '激活用户提交订金额'
                
                );
                
                 //发送其他渠道的（没有广告排期的订单日报）到指定邮箱
                $opOtherRow = $this->dayMemberTypeOther($startTime,$productCode);
                $keyOpOtherArr = array('渠道类型', '订单金额', '订单量', 
                                  '客单价', '激活量', '激活用户提交订单量', '激活用户提交订金额'
                );
                
                //广告投放表
                $adRow = $this->dayAd($startTime, $productCode);
                
                //付费广告表
                $adPaidRow = $adRow['rowPaid'];
                $keyAdPaidArr = array('广告渠道', 'ROI', '订单金额', '订单量', '客单价', '广告成本');
                
                //操作系统报表
                $osRow = $this->dayOs($startTime,$productCode);
                $keyOsArr = array('操作系统', '订单金额', '订单量', '客单价', '激活量', '激活用户提交订单量', '激活用户提交订金额');
                
                
                //发送其他渠道的（没有广告排期的订单日报）到指定邮箱
                $opOtherErrorRow = $this->dayMemberTypeOtherError($startTime,$productCode);
                $keyOpOtherErrorArr = array('SourceId', '订单金额' ,'订单量', 
                                  '客单价', '激活量', '激活用户提交订单量', '激活用户提交订金额'
                );
                
                //获取月明细报表
                $monthReportRow = $this->monthReport($productCode);
                $keyMonthReportRow = array('日期', 'ROI','当天总提交订单金额',
                    '当天总提交订单量','客单价','广告成本',
                    '当天激活量','当天激活用户提交订单量',
                    '当天激活用户提交订单转化率',    '当天激活用户提交订单金额',
                    '当天ROI','启动到订单转化率',
                     '启动次数','启动人数','人均启动','活跃老用户数','操作系统'                                    
                );
                //获取月明细报表-有广告排期的
                $monthAdReportRow = $this->monthAdReport($productCode);
                
                //写入到日运营EXCEL文件
                
                $opFile = $this->_model->writeToExcel('op', $this->getFileDay().' '.$productName.'-日运营报表',$opRow,$productCode,$keyOpArr);
                $adPaidFile = $this->_model->writeToExcel('adPaid', $this->getFileDay().' '.$productName.'-广告投放报表',$adPaidRow,$productCode,$keyAdPaidArr);
                $osFile = $this->_model->writeToExcel('os', $this->getFileDay().' '.$productName.'-操作系统报表',$osRow,$productCode,$keyOsArr);
                $opOtherFile = $this->_model->writeToExcel('opOther', $this->getFileDay().' '.$productName.'-日运营报表-其他渠道',$opOtherRow,$productCode,$keyOpOtherArr);
                 //写入到日运营EXCEL文件
                $opOtherErrorFile = $this->_model->writeToExcel('opOtherError', $this->getFileDay().' '.$productName.'-日运营报表-异常渠道',$opOtherErrorRow,$productCode,$keyOpOtherErrorArr);

                $yestoday = date('Y-m-d',strtotime("-1 day"));
                //收集其他简报的数组
                $simpleReportRows = array(
                                    'opRow' => array('name'=>$this->getFileDay().' - '.$productName.' - 运营日报','title'=>$keyOpArr,'lines'=>$opRow),
                                    'opOtherRow' => array('name'=>$this->getFileDay().' - '.$productName.' - 广告投放日报','title'=>$keyOpOtherArr,'lines'=>$opOtherRow),
                                    'adPaidRow' => array('name'=>$this->getFileDay().' - '.$productName.' - 其他渠道日报','title'=>$keyAdPaidArr,'lines'=>$adPaidRow),
                                    'osRow' => array('name'=>$this->getFileDay().' - '.$productName.' - 操作系统报表','title'=>$keyOsArr,'lines'=>$osRow)    
                                    );
                //写入到月运营报表EXCEL文件
                $monthReportFile = $this->_model->writeToExcelMonth('monthReport', $this->getMonthReportTitle().' '.$productName.' 月运营报表 ',$monthReportRow, $monthAdReportRow,$productCode,$productName,$keyMonthReportRow, $simpleReportRows);

                //发送邮件到用户邮件
                $mailList = $this->_productModel->getReportMailList($productCode);
                $to = array();
                foreach ($mailList as $mail) {
                    $to[]=array(
                    'name'=>$mail,'email'=>$mail
                     );
                }
                           
                if (count($to)) {
                    //收集所有表格数据
                    $downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/data/dayData/';
                    $data = array();
                    $data[]=array(
                    'title'=>'日运营报表',
                    'headLine' => $keyOpArr,
                    'bodyLines' => $opRow,
                    'file' => $downUrl.$opFile
                    );
                    $data[]=array(
                    'title' => '广告投放报表',
                    'headLine' => $keyAdPaidArr,
                    'bodyLines' => $adPaidRow,
                    'file' => $downUrl.$adPaidFile
                    );
                    $data[]=array(
                    'title' => '操作系统报表',
                    'headLine' => $keyOsArr,
                    'bodyLines' => $osRow,
                    'file' => $downUrl.$osFile
                    );
                    $data[] = array(
                    'title' => '日运营报表 - 免费渠道明细',
                    'headLine' => $keyOpOtherArr,
                    'bodyLines' => $opOtherRow,
                    'file' => $downUrl.$opOtherFile
                    );
                    
                    //写入到日报的HTML文件
                    $dayReportHtmlFile = $this->_model->writeToHtmlFile($data, $productName.' - 日报',$productName, PUBLIC_PATH . "/data/dayData/".$this->getFileDay().'_'.$productCode."_dayReportHtml.html");
                    $dataMonth = array();
                    $dataMonth[] = array(
                    'title'=>'月运营报表',
                    'headLine' => $keyMonthReportRow,
                    'bodyLines' => $monthReportRow,
                    'file' => ''
                    );
                    //写入到月报的HTML文件
                    $monthReportHtmlFile =  $this->_ddhModel->writeToHtmlFile($dataMonth, $productName.' - 月报',$productName, PUBLIC_PATH . "/data/dayData/".$this->getFileDay().'_'.$productCode."_monthReportHtml.html");
                    //发送运营日报表邮件 
                    $mainMail = $product['reportMail']? $product['reportMail']:$to[0]; 
                    
                     //加载ZIP类
                      Zend_Loader::loadClass('Project_PclZip');
                      $attFilePath = PUBLIC_PATH . "/data/dayData/".$productCode.'_'.date('YmdHis').'_archive.zip';
                      if(file_exists($attFilePath)) {
                          unset($attFilePath);
                      }
                      $archive = new Project_PclZip($attFilePath);
                      $vList[] = $archive->add(PUBLIC_PATH . "/data/dayData/".$monthReportFile, 
                                    PCLZIP_OPT_REMOVE_PATH, PUBLIC_PATH . "/data/dayData/"); 
                                    
                      $vList[] = $archive->add($monthReportHtmlFile, 
                                    PCLZIP_OPT_REMOVE_PATH, PUBLIC_PATH . "/data/dayData/"); 
                                    
                      $vList[] = $archive->add($dayReportHtmlFile, 
                                    PCLZIP_OPT_REMOVE_PATH, PUBLIC_PATH . "/data/dayData/");      
                                             
                      foreach ($vList as $item) {
                          if ($item == 0) {
                              die("Error : ".$archive->errorInfo(true));
                          }
                      }
                      $atts = array(
                            array('filename'=>$this->getFileDay().'_'.$productCode.'_att.zip','path'=>$attFilePath,'type'=>'application/zip')
                        ); 
                        
                    $this->_model->sendMail('', $monthReportHtmlFile, $dayReportHtmlFile
                    ,$productName.' '.$startTime.' 运营日报','运营日报',$productName,$mainMail,$to,$data,$atts);      
                }

                //发送邮件到用户邮件
                $mailListOther = $this->_configs['project']['reportTestMail'];
                $toOtherError = array();
                foreach ($mailListOther as $mail) {
                    $toOtherError[]=array(
                    'name'=>$mail,'email'=>$mail
                     );
                }

                if (count($toOtherError)) {
                    //收集所有表格数据
                    $downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/data/dayData/';
                    $dataOther = array();
                    $dataOther[]=array(
                    'title'=>'日运营报表',
                    'headLine' => $keyOpOtherErrorArr,
                    'bodyLines' => $opOtherErrorRow,
                    'file' => $downUrl.$opOtherErrorFile
                    );
                    //发送运营日报表邮件        
                    $mainMailOther = $toOtherError[0]['email'];
                    array_shift($toOtherError);
                    if (count($opOtherErrorRow)) {
                        $this->_model->sendMail('','',''
                    ,$productName.' '.$startTime.' 运营日报-异常渠道','运营日报-异常渠道',$productName,$mainMailOther,$toOtherError,$dataOther,null,2);
                    }
                    
                }  
                
            }
        } exit();
    }
    
    /**
     * 日运营报表-日
     */
    public function dayMemberType($startTime,$productCode)
    {               
        $rows = $this->_model->getDayMemberType($startTime,$productCode);
        $totalRow = array();
        $memberType = array('广告渠道','免费渠道');
        for ($i=0; $i<count($rows); ++$i) {
            array_unshift($rows[$i], $memberType[$i]);
            foreach ($rows[$i] as $key=>$val) {
                if ($key != 'memberType') {
                    @$totalRow[$key] += floatval($val);  
                }          
            }           
        }
         //客单价统计
        @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
        
        $rows[$i] = $totalRow;
                       
        array_unshift($rows[$i], '总计');       
        return $rows;   
    }
    
     /**
     *日报 - 非排期渠道
     */
    public function dayMemberTypeOther($startTime,$productCode)
    {
        $totalRow = array();
        $rowsPaid = $this->_model->getMemberTypeOther($startTime, $productCode);
        
        if (count($rowsPaid)) {
            for ($i=0; $i<count($rowsPaid); ++$i) {           
                foreach ($rowsPaid[$i] as $key=>$val) {
                    if ($key != 'name') {
                        @$totalRow[$key]+=floatval($val);
                    } 
                }           
            }
              //客单价统计
            @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
              
            $rowsPaid[$i] =$totalRow;
              
            array_unshift($rowsPaid[$i], '总计');
        }
        
        return $rowsPaid;
        
    }
    
     /**
     *日报 - SOURCEID不存在的渠道信息
     */
    public function dayMemberTypeOtherError($startTime,$productCode)
    {
        $totalRow = array();
        $rowsPaid = $this->_model->getMemberTypeOtherError($startTime, $productCode);
        
        if (count($rowsPaid)) {
            for ($i=0; $i<count($rowsPaid); ++$i) {           
                foreach ($rowsPaid[$i] as $key=>$val) {
                    if ($key != 'sourceId' && $key != 'sourceSubId') {
                        @$totalRow[$key]+=floatval($val);
                    } 
                }           
            }
              //客单价统计
            @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
              
            $rowsPaid[$i] =$totalRow;
            array_unshift($rowsPaid[$i], '总计');
        }
        
        return $rowsPaid;
    }
    
     /**
     * 广告投放-日
     */
    public function dayAd($startTime,$productCode)
    {               
        //付费广告
        $totalRow = array();
        $rowsPaid = $this->_model->getDayPaidAd($startTime, $productCode);
        
        if (count($rowsPaid)) {
            for ($i=0; $i<count($rowsPaid); ++$i) {           
                foreach ($rowsPaid[$i] as $key=>$val) {
                    if ($key != 'name') {
                        @$totalRow[$key]+=floatval($val);
                    } 
                }           
            }
              //客单价统计
            @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
              
            $rowsPaid[$i] =$totalRow;
              
            array_unshift($rowsPaid[$i], '总计');
        }
        return array(
        'rowPaid'=>$rowsPaid
        );
        
    }
    
   /**
     * 操作系统 - 日
     */
    public function dayOs($startTime,$productCode)
    {
        //日运营按操作系统统计报表
        $totalRow = array();
        $rows = $this->_model->getDayOs($startTime, $productCode);      
        if (count($rows)) {
            for ($i=0; $i<count($rows); ++$i) {           
                foreach ($rows[$i] as $key=>$val) {
                    if ($key != 'osName') {
                        @$totalRow[$key]+=floatval(($val));
                    } 
                }           
            }
             //客单价统计
            @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
            $rows[$i] = $totalRow;
            array_unshift($rows[$i], '总计');
        }
        
        return $rows;   
    }
    
    /**
     * 输出产品APP端真实订单数据
     * 统计出上一个月，每天的订单数量和销售额
     */
    public function monthOrderChartAction()
    {
        
        $this->_productcode = $productCode = $this->_request->get('productcode');
        $this->_currAction = 'month-order-chart';
        
        if (Application_Model_UserLogin::isLogined()) {
            $startEnd = $this->getStartEndStamp();
            $startTime = $startEnd['startTime'] ;
            $endTime = $startEnd['endTime'] ;
            
            //总数据
            $series = array();
            $okOrderAmount = array();
            $okOrderNum = array();
            $currDay = array();
            for ($i=$startTime; $i<=$endTime; $i=$i+24*60*60) {
                $date = date('Y-m-d',$i);
                //订单每日汇总数据
                $dayData = $this->_model->getProductDayData($productCode,$date);
                $okOrderAmount[] = floatval($dayData['okOrderAmount']);
                $okOrderNum[] = intval($dayData['okOrderNum']);
                $currDay[] = date('d',$i);
            }
            $series[] = array(
            'name'=>'销售额',
            'data'=>$okOrderAmount
            );
            
            $series[] = array(
            'name'=>'订单数',
            'yAxis'=>1,
            'data'=>$okOrderNum
            );        
            $product = $this->_productModel->fetchRow("code='{$productCode}'");
            $this->view->productName = $product['name'];
            $jsonString = json_encode($series);
            $this->view->data = $jsonString;
            $this->view->categories = json_encode($currDay);
            $this->view->timeDesc = '最近一个月'; 
            $this->logout();
        } else {
            redirect($this->view->projectUrl(array('action'=>'login','productcode'=>$this->_productcode,'currAction'=>$this->_currAction)));
            exit();
        }
    }
    /**
     * 上个月的每日激活量
     */
    public function monthInstallNumAction()
    {
        $this->_productcode = $productCode = $this->_request->get('productcode');
        $this->_currAction = 'month-install-num';
        if (Application_Model_UserLogin::isLogined()) {
            $startEnd = $this->getStartEndStamp();
            $startTime = $startEnd['startTime'] ;
            $endTime = $startEnd['endTime'];
            
            //总数据
            $series = array();
            //广告渠道
            $adInstallNum = array();
            //免费渠道
            $freeInstallNum = array();
            for ($i=$startTime; $i <= $endTime; $i = $i+24*60*60) {
                $date = date('Y-m-d',$i);
                $dayData = $this->_model->getProductInstallNum($productCode,$date);
                $adInstallNum[] = $dayData['adInstallNum'];
                $freeInstallNum[] = $dayData['freeInstallNum'];
                $currDay[] = date('d',$i);
            }
            $series[] = array(
            'name'=>'广告渠道',
            'data'=>$adInstallNum
            );
            $adData = '';
            foreach ($series[0]['data'] as $item) {
                $adData .= intval($item).',';
            }
            $adData = substr($adData, 0, strlen($adData)-1);
            $series[0]['data'] = $adData;
            
            $adData = '';
            $series[] = array(
            'name'=>'免费渠道',
            'data'=>$freeInstallNum
            );
            foreach ($series[1]['data'] as $item) {
                $adData .= intval($item).',';
            }
            $adData = substr($adData, 0, strlen($adData)-1);
            $series[1]['data'] = $adData;
            $this->view->series = $series;
            $product = $this->_productModel->fetchRow("code='{$productCode}'");
            $this->view->productName = $product['name'];
            $jsonString = json_encode($series);
            $this->view->data = $jsonString;
            $this->view->categories = json_encode($currDay);
            $this->view->timeDesc = '最近一个月'; 
            $this->logout();
        }  else {
            redirect($this->view->projectUrl(array('action'=>'login','productcode'=>$this->_productcode,'currAction'=>$this->_currAction)));
            exit();
        }
    }
    /**
     * 报表文件下载
     */
    public function downReportAction()
    {
        $this->_reportFile = $this->_request->get('file');
        $this->_currAction = 'down-report';
        
         if (Application_Model_UserLogin::isLogined()) {
             echo '用户验证成功，请下载。';
             //$downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/yek_mob/data/dayData/';
             $downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/data/dayData/';
             $this->logout();
             redirect($downUrl . $this->_request->get('file'));
             exit();
         } else {
            redirect($this->view->projectUrl(array('action'=>'login-file','file'=>$this->_reportFile)));
            exit();
        }
    }
    
    /**
     * 获取最近30天的明细报表
     * Enter description here ...
     * @param unknown_type $startTime
     * @param unknown_type $productCode
     */
    public function monthReport($productCode)
    {
        $start = $this->getPositionStamp();
        $totalRow = array();
        $avgRow = array();
        $rows = array();
        for ($i = 0; $i< date('d',$start); ++$i) {
            $startTime = date('Y-m-d',$start-$i*24*60*60);
            $rows[] = $this->_ddhModel->getDayMemberAdDetail($productCode,$startTime);
        }
        
        //获取总计
        $startTime = date("Y-m-d",$this->getPositionStamp());
        $endTime = date("Y-m-01",$this->getPositionStamp());
        $totalRow = $this->_model->getMonthTotal($productCode,$startTime,$endTime);
        //获取平均
        $avgRow = $this->_model->getMonthAvg($productCode,$startTime,$endTime);
        $rows['total'] = $totalRow;
        $rows['avg'] = $avgRow;
        return $rows;
    }
    /**
     * 获取最近30天的明细报表(广告投放)
     * Enter description here ...
     * @param unknown_type $startTime
     * @param unknown_type $productCode
     */
    public function monthAdReport($productCode)
    {
        $start = $this->getPositionStamp();
        $totalRow = array();
        $avgRow = array();
        $rows = array();
        for ($i = 0; $i< date('d',$start); ++$i) {
            $startTime = date('Y-m-d',$start-$i*24*60*60);
            $rows[] = $this->_model->getAdDayMemberAdDetail($productCode,$startTime);
        }
        //获取总计
        $startTime = date("Y-m-d",$this->getPositionStamp());
        $endTime = date("Y-m-01",$this->getPositionStamp());
        $totalRow = $this->_model->getAdMonthTotal($productCode,$startTime,$endTime);
        //获取平均
        $avgRow = $this->_model->getAdMonthAvg($productCode,$startTime,$endTime);
        $rows['total'] = $totalRow;
        $rows['avg'] = $avgRow;
        return $rows;
    }
    
    /**
     * 退出
     * 
     * @return void
     */
    public function logout()
    {
        $userLoginModel = new Application_Model_UserLogin();
        $userLoginModel->logout();
    }
}